package com.weixing.mall.provider.controller;

import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.properties.WeiXingProperties;
import com.weixing.mall.core.properties.ali.OssProperties;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.upload.AliOssUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传通用类
 *
 * @Author: kfc
 * @Description: <br/>
 * Date:Create in 2019/8/21 16:37
 * @Modified By:
 */

@RestController
@RequestMapping("upload")
public class UploadController extends BaseController {

    @Autowired
    private WeiXingProperties weiXingProperties;

    @PostMapping("")
    public Result upload(HttpServletRequest request, @RequestParam("file") MultipartFile file){
        // 文件大小
        long size = file.getSize();
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 文件类型
        String contentType = file.getContentType();
        String fileName = UUID.randomUUID().toString().replaceAll("-", "")   + originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            OssProperties oss = weiXingProperties.getAli().getOss();
            boolean upload = new AliOssUpload(oss).upload(oss.getBucket().getGoods(), fileName, file.getInputStream());
            return ResultUtil.success(fileName).setData(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResultUtil.error(ResultCodeEnum.CODE_10013001);
    }
}
